/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package enterprise.web_jpa_war.servlet;

import enterprise.web_jpa_war.entity.Adherent;
import enterprise.web_jpa_war.entity.Demande;
import enterprise.web_jpa_war.entity.Emprunt;
import enterprise.web_jpa_war.entity.Item;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import javax.persistence.TemporalType;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.transaction.NotSupportedException;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;

/**
 *
 * @author jeddi
 */
@WebServlet(name = "ConfirmCart", urlPatterns = {"/ConfirmCart"})
public class ConfirmCart extends HttpServlet {

    @PersistenceUnit
    private EntityManagerFactory emf;
    
    @Resource
    private UserTransaction utx;
    
    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
            
        EntityManager em = null;
        
        
        try {
            utx.begin();
            
            em = emf.createEntityManager();
            
            // Récupérer le User
            Adherent currentUser = null;
            HttpSession bdaSession = request.getSession();
            if(bdaSession.getAttribute("authUser") == null) {
                request.getRequestDispatcher("index.jsp").forward(request, response);
            } else currentUser = (Adherent)(bdaSession.getAttribute("authUser"));
            
            // Récupérer la Demande
            Long id = Long.parseLong(request.getParameter("idDemande"));
            
            String query = "select d from Demande d where d.numDemande = :id";
            Query emQuery = em.createQuery(query);
            emQuery.setParameter("id", id);
            
            Demande result = (Demande)(emQuery.getSingleResult());
            if(result == null) {
                request.getRequestDispatcher("index.jsp").forward(request, response);
            }
            
            // Check si l'oeuvre est dispo
            query = "select i from Item i where i.oeuvre.id = :id and i.dispo = true";
            emQuery = em.createQuery(query);
            emQuery.setParameter("id", result.getOeuvre().getId());
            
            Item empruntItem = null;
            List<Item> items = (List<Item>) emQuery.getResultList();
            
            if(items != null && items.size() > 0){
                empruntItem = items.get(0);
            // Rendre l'item indispo
            query = "update Item i set i.dispo = false where i.oeuvre.id = :id and i.isbn= :isbn";
            emQuery = em.createQuery(query);
            emQuery.setParameter("id", result.getOeuvre().getId());
            emQuery.setParameter("isbn", empruntItem.getIsbn());
            emQuery.executeUpdate();
            
            // Créer l'emprunt
            Emprunt e = new Emprunt(currentUser, empruntItem, new Date(), Boolean.TRUE, Boolean.FALSE);
            em.persist(e);
            
            em.createQuery("update Demande d set d.validee = true where d.numDemande = :id").setParameter("id", id).executeUpdate();
            
            utx.commit();
            
            // Afficher le résultat
            request.getRequestDispatcher("LoadCart").forward(request, response);
            }
            else{
                emf.createEntityManager();
                em.remove(result);
                utx.commit();
                 PrintWriter out = response.getWriter();
                    try {
                        out.println("<html>");
                        out.println("<head>");
                        out.println("<title>Servlet ConfirmCart</title>");
                        out.println("</head>");
                        out.println("<body>");
                        out.println("<h1>Servlet ConfirmCart at " + request.getContextPath() + "</h1>");
                        out.println("<p>Erreur lors de la confirmation du panier.</p>");
                        out.println("<a href='LoadCart'><strong>retour au panier.</strong></a>");
                        out.println("</body>");
                        out.println("</html>");
                    } finally {            
                        out.close();
                    }
            }
        } catch(NoResultException nex) {
            /*try {
                utx.begin();
                emf.createEntityManager();
                query = "delete from Demande d where d.numDemande = :id";
                emQuery = em.createQuery(query);
                emQuery.setParameter("id", id);
                emQuery.executeUpdate();
                request.getRequestDispatcher("index.jsp").forward(request, response);
                utx.commit();
            } catch (NotSupportedException ex) {
                Logger.getLogger(ConfirmCart.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SystemException ex) {
                Logger.getLogger(ConfirmCart.class.getName()).log(Level.SEVERE, null, ex);
            }
            catch(Exception e){}*/
            
        } catch (Exception ex) {
            throw new ServletException(ex);
        } finally {
            if(em != null) {
                em.close();
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
